package com.mop.dinnerbook.dao;

import com.mop.dinnerbook.bean.ExportBean;
import com.mop.dinnerbook.bean.ExportComparator;
import java.io.File;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import com.mop.dinnerbook.bean.Manager;
import com.mop.dinnerbook.bean.Member;
import com.mop.dinnerbook.bean.Project;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

/*
 管理员操作业务类
 */
public class ManageDAO extends BaseDAO{
    /*
     认证管理员用户名和密码
     */
	public boolean authorize(String manageName, String managePass) {
		int result = 0;
		String sql = "select count(1) from manager where mgname ='"
				+ manageName + "' and mgPass='" + managePass + "'";
		try {
			result = (Integer) executeSelectObject(sql, new Processor() {
                                @Override
				public Object product(ResultSet rst) throws SQLException {
					int total = rst.getInt(1);
					return total;
				}
			});
		} catch (SQLException e) {
                        System.out.println(sql);
			e.printStackTrace();
		}
		return result > 0;
	}
/*
 根据管理员名称获取管理员实例
 */
	public Manager getManager(String manageName) {
		Manager manager = null;
		String sql = "select mgid,mgname,mgpass from manager where mgname ='"
				+ manageName + "'";
		try {
			manager = (Manager) executeSelectObject(sql, new Processor() {
				public Object product(ResultSet rst) throws SQLException {
					Manager m = new Manager();
					m.setMgid(rst.getInt(1));
					m.setMgname(rst.getString(2));
					m.setPassword(rst.getString(3));
					return m;
				}
			});
		} catch (SQLException e) {
                        System.out.println(sql);
			e.printStackTrace();
		}
		return manager;
	}

/*
 根据时间段导出订餐列表数据
 */   
        public String exportByDate(String fdir,Date begin,Date end) {
		MemberDAO dao = new MemberDAO();
		List memList = dao.getAllBookedMemberByDate(begin,end);
                List<ExportBean> result = toExportBean(memList);
		String fname = exportCsvByDate(fdir,result);
		return fname;
	}
        
    private List<ExportBean> toExportBean(List memList) {
        List<ExportBean> list = new ArrayList<ExportBean>();
        Iterator iter = memList.iterator();
        DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd号");
        while (iter.hasNext()) {
                Project project = (Project) iter.next();
                Iterator _iter = project.getMembers().iterator();
                while (_iter.hasNext()) {
                        Member member = (Member) _iter.next();
                        ExportBean bean = new ExportBean();
                        bean.setFid(member.getFloor().getFid());
                        bean.setFloor(member.getFloor().getFname());
                        bean.setMid(member.getMid());
                        bean.setMname(member.getMname());
                        bean.setPid(project.getPid());
                        bean.setPname(project.getPname());
                        bean.setDid(member.getDepartment().getDid());
                        bean.setDname(member.getDepartment().getDname());
                        String dt = formatter.format(member.getRdate());
                        bean.setDate(dt);
                        list.add(bean);
                }
        }
        Collections.sort(list,new ExportComparator());
        return list;
    }
    
/*
 根据实际段导出csv格式的订餐数据
 */
        public String exportCsvByDate(String fdir,List<ExportBean> result) {
                File dirf = new File(fdir);
                if(!dirf.exists())dirf.mkdir();
		String fname = generateFilename() + ".csv";
		PrintWriter out = null;
		try {
                    File f = new File(fdir + fname);
                    f.createNewFile();
                    out = new PrintWriter(f);
                    Iterator<ExportBean> iter = result.iterator();
                    out.println("时间,楼层,编号,项目组,岗位,成员,签名");
                    while (iter.hasNext()) {
                       ExportBean bean = iter.next();
                       out.println(bean.getDate()+","+bean.getFloor()+","+bean.getMid()+","+bean.getPname()+","+bean.getDname()+","+bean.getMname()+",");
                    }
                    out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fname;
	}

/*
 生成导出文件名
 */
	private String generateFilename() {
		String result = "Dinner-";
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		result = result + format.format(Calendar.getInstance().getTime());
		String _result = "";
		try {
			_result = new String(result.getBytes(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return _result;
	}
/*
 增加成员
 */
	public boolean addMember(int pid, int did ,String mname,int fid) {
		if (memberExisted(pid, mname))
			return false;
		System.out.println("----------------" + mname + "-----------------------");
		String isql = "insert into member(mid,mname,pid,did,fid) values(NULL,'" + mname
				+ "'," + pid + "," + did + "," + fid + ")";
		boolean result = false;
		try {
			result = executeInsert(isql) > 0;
		} catch (Exception e) {
                        System.out.println(isql);
			e.printStackTrace();
		} 
		return result;
	}
/*
 判断成员姓名是否已经存在
 */
	public boolean memberExisted(int pid, String mname) {
		int result = 0;
		System.out.println("----------------" + mname + "-----------------------");
		String sql = "select count(1) from member where valid = 1 and pid=" + pid
				+ " and mname = '" + mname + "'";
		try {
			result = (Integer) executeSelectObject(sql, new Processor() {
				public Object product(ResultSet rst) throws SQLException {
					int total = rst.getInt(1);
					return total;
				}
			});
		} catch (SQLException e) {
                        System.out.println(sql);
			e.printStackTrace();
		}
		return result > 0;
	}
        /*
         删除成员，软删除
         */
        public boolean deleteMember(int mid){
                String dsql = "update member set valid = 0 where mid="+mid;
                boolean result = false;
                try {
                    result = executeUpdate(dsql) > 0;
                } catch (Exception e) {
                    System.out.println(dsql);
                    e.printStackTrace();
                } 
                return result;
        }
        /*
         增加主项目组
         */
        public boolean addProject(String pname){
            if (projectExisted(pname))
			return false;
		String isql = "insert into project(pid,pname) values(NULL,'" + pname + "')";
		boolean result = false;
		try {
			result = executeInsert(isql) > 0;
		} catch (Exception e) {
                        System.out.println(isql);
			e.printStackTrace();
		} 
		return result;
        }
        /*
         判断主项目组名是否已经存在
         */
        public boolean projectExisted(String pname){
		int result = 0;
		String sql = "select count(1) from project where pname='"+pname+"'";
		try {
			result = (Integer) executeSelectObject(sql, new Processor() {
				public Object product(ResultSet rst) throws SQLException {
					int total = rst.getInt(1);
					return total;
				}
			});
		} catch (SQLException e) {
                        System.out.println(sql);
			e.printStackTrace();
		}
		return result > 0;
        }


        
}
